// 全局变量
let selectedPath = '';
let userSettings = null;

// 获取用户设置
async function initializeUserSettings() {
    try {
        userSettings = await electronAPI.getUserSettings();
    } catch (error) {
        console.error('获取用户设置失败:', error);
        userSettings = { email: 'unknown', site: 'unknown' };
    }
}

// 初始化用户设置
initializeUserSettings();

// 选择路径函数
async function selectPath() {
    try {
        // 确保selectedPath已初始化
        if (typeof selectedPath === 'undefined') {
            selectedPath = '';
        }
        
        if (window.fileAPI && window.fileAPI.showOpenDialog) {
            const result = await window.fileAPI.showOpenDialog({
                title: '选择目标文件夹',
                properties: ['openDirectory']
            });
            
            if (result.success && result.data && !result.data.canceled && result.data.filePaths && result.data.filePaths.length > 0) {
                selectedPath = result.data.filePaths[0];
                document.getElementById('targetPath').value = selectedPath;
                showStatus('路径选择成功: ' + selectedPath, 'success');
            } else if (result.success && result.data && result.data.canceled) {
                console.log('用户取消了文件夹选择');
            } else {
                console.error('选择文件夹失败:', result.error || '未知错误');
                showStatus('选择文件夹失败，请重试', 'error');
            }
        } else {
            console.error('文件选择API不可用');
            showStatus('文件选择功能不可用，请手动输入路径', 'error');
        }
    } catch (error) {
        console.error('选择路径失败:', error);
        showStatus('选择路径失败: ' + error.message, 'error');
    }
}

// 创建文件夹函数
async function createFolders() {
    const targetPath = document.getElementById('targetPath').value.trim();
    const folderNamesText = document.getElementById('folderNames').value.trim();
    
    // 验证输入
    if (!targetPath) {
        showStatus('请选择或输入目标路径', 'error');
        return;
    }
    
    if (!folderNamesText) {
        showStatus('请输入文件夹名称', 'error');
        return;
    }
    
    // 解析文件夹名称
    const folderNames = folderNamesText.split('\n')
        .map(name => name.trim())
        .filter(name => name.length > 0);
    
    if (folderNames.length === 0) {
        showStatus('请输入有效的文件夹名称', 'error');
        return;
    }
    
    showStatus(`准备创建 ${folderNames.length} 个文件夹...`, 'info');
    
    // 禁用创建按钮
    const createBtn = document.querySelector('.create-btn');
    createBtn.disabled = true;
    createBtn.textContent = '创建中...';
    
    try {
        // 确保用户设置已加载
        if (!userSettings) {
            await initializeUserSettings();
        }
        
        console.log(`targetPath: ${targetPath}`, `folderNames: ${folderNames}`)
        const { success, data, error } = await pluginAPI.runPluginScript({
            pluginName: 'batch-newFolder',
            script: './core.js',
            args: [targetPath, folderNames, userSettings]
        });
        
        if (success) {
            // 显示结果
            displayResults({
                success: data.results.filter(r => r.success).map(r => r.folderName),
                failed: data.results.filter(r => !r.success).map(r => ({
                    name: r.folderName,
                    reason: r.error
                })),
                skipped: []
            });
            
            showStatus(`创建完成！成功: ${data.summary.successful}, 失败: ${data.summary.failed}`, 'success');
        } else {
            showStatus('批量创建失败1: ' + error, 'error');
        }
        
    } catch (error) {
        console.error('批量创建文件夹失败:', error);
        showStatus('批量创建失败2: ' + error.message, 'error');
    } finally {
        // 恢复创建按钮
        createBtn.disabled = false;
        createBtn.textContent = '批量创建文件夹';
    }
}

// 验证文件夹名称
function isValidFolderName(name) {
    // 简化的前端验证，详细验证在后端进行
    if (!name || name.trim() === '') {
        return false;
    }
    
    // 基本的无效字符检查
    const invalidChars = /[<>:"/\\|?*]/;
    if (invalidChars.test(name)) {
        return false;
    }
    
    return true;
}

// 显示操作结果
function displayResults(results) {
    let message = '';
    let type = 'success';
    
    if (results.success.length > 0) {
        message += `成功创建 ${results.success.length} 个文件夹`;
    }
    
    if (results.skipped.length > 0) {
        if (message) message += '\n';
        message += `跳过 ${results.skipped.length} 个已存在的文件夹`;
    }
    
    if (results.failed.length > 0) {
        if (message) message += '\n';
        message += `失败 ${results.failed.length} 个文件夹`;
        type = results.success.length > 0 ? 'success' : 'error';
        
        // 显示失败详情
        const failedDetails = results.failed.map(item => 
            `${item.name}: ${item.reason}`
        ).join('\n');
        
        console.log('创建失败的文件夹详情:', failedDetails);
    }
    
    showStatus(message, type);
    
    // 显示监控状态（实时监控已在创建过程中完成）
    showMonitoringStatus({ success: true, message: '实时监控已启用' }, results);
    
    // 如果有成功创建的文件夹，询问是否打开目标文件夹
    if (results.success.length > 0) {
        setTimeout(() => {
            if (confirm('文件夹创建完成！是否打开目标文件夹查看？')) {
                openFolder(selectedPath);
            }
        }, 1000);
    }
}

// 打开文件夹
async function openFolder(folderPath) {
    try {
        if (window.fileAPI && window.fileAPI.showItemInFolder) {
            await window.fileAPI.showItemInFolder(folderPath);
        } else {
            console.error('文件操作API不可用');
            showStatus('打开文件夹功能不可用', 'error');
        }
    } catch (error) {
        console.error('打开文件夹失败:', error);
        showStatus('打开文件夹失败: ' + error.message, 'error');
    }
}

// 显示监控状态
function showMonitoringStatus(monitoringResult, results) {
    const monitoringDiv = document.getElementById('monitoring-status');
    const monitoringInfo = document.getElementById('monitoring-info');
    
    if (!monitoringDiv || !monitoringInfo) return;
    
    const successCount = results.success.length;
    const failCount = results.failed.length;
    const skippedCount = results.skipped.length;
    const totalCount = successCount + failCount + skippedCount;
    
    let statusClass = monitoringResult.success ? 'monitoring-success' : 'monitoring-failed';
    let statusText = monitoringResult.success ? '✓ 已记录' : '✗ 未记录';
    
    monitoringInfo.innerHTML = `
        <div>操作统计: 总计 ${totalCount} 个文件夹</div>
        <div>成功: <span class="monitoring-success">${successCount}</span> | 
             失败: <span class="monitoring-failed">${failCount}</span> | 
             跳过: ${skippedCount}</div>
        ${!monitoringResult.success ? `<div style="color: #f44336; margin-top: 5px;">原因: ${monitoringResult.message}</div>` : ''}
    `;
    
    monitoringDiv.style.display = 'block';
}

// 显示状态信息
function showStatus(message, type = 'info') {
    const statusEl = document.getElementById('status');
    statusEl.textContent = message;
    statusEl.className = `status ${type}`;
    statusEl.style.display = 'block';
    
    // 3秒后自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            statusEl.style.display = 'none';
        }, 3000);
    }
}

// 窗口控制函数
function minimizeWindow() {
    if (window.electronAPI && window.electronAPI.minimizeWindow) {
        window.electronAPI.minimizeWindow();
    }
}

function toggleMaximize() {
    if (window.electronAPI && window.electronAPI.toggleMaximize) {
        window.electronAPI.toggleMaximize();
    }
}

function closeWindow() {
    if (window.electronAPI && window.electronAPI.closeWindow) {
        window.electronAPI.closeWindow();
    }
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', async function() {    
    // 监听文件夹名称输入框的变化
    const folderNamesInput = document.getElementById('folderNames');
    folderNamesInput.addEventListener('input', function() {
        const lines = this.value.split('\n').filter(line => line.trim().length > 0);
        if (lines.length > 0) {
            document.querySelector('.create-btn').disabled = false;
        }
    });
    
    // 支持拖拽文件夹到路径输入框
    const pathInput = document.getElementById('targetPath');
    
    pathInput.addEventListener('dragover', function(e) {
        e.preventDefault();
        e.stopPropagation();
        this.style.borderColor = '#e81cff';
    });
    
    pathInput.addEventListener('dragleave', function(e) {
        e.preventDefault();
        e.stopPropagation();
        this.style.borderColor = '#333';
    });
    
    pathInput.addEventListener('drop', function(e) {
        e.preventDefault();
        e.stopPropagation();
        this.style.borderColor = '#333';
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            const file = files[0];
            if (file.type === '' && file.size % 4096 === 0) { // 可能是文件夹
                selectedPath = file.path;
                this.value = selectedPath;
                showStatus('路径设置成功: ' + selectedPath, 'success');
            } else {
                showStatus('请拖拽文件夹，不是文件', 'error');
            }
        }
    });
    
    console.log('批量新建文件夹插件已加载');
});

// 导出函数供HTML调用
window.selectPath = selectPath;
window.createFolders = createFolders;
